<?php
namespace Frieza\Modules\Activity\Controllers;

use Doraemon\cache\Activity\TMallCard as cTMallCard;
use Doraemon\model\Activity\UserGrowthCards;
use Doraemon\service\Activity\NewUserGrowth;
use Doraemon\tools\Crypt;
use Doraemon\tools\Log;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class CardsController
{
    public function index(Request $request, Content $content, Form $form)
    {
        $form->disableReset();
        $this->_getForm($form);
        $form->action('/admin/activity/cards/save');
        $tab = new Tab();
        $tab->add('天猫卡', $form->render(), true);
        $content->row($tab);
        return $content
            ->header('天猫卡上传')
            ->description(' ');

    }

    public function save(Request $request)
    {
        $params = $request->all();
        $file = $params['excel'];
        $inputFileType = \PHPExcel_IOFactory::identify($file);
        $objReader = \PHPExcel_IOFactory::createReader($inputFileType);
        $objExcel = $objReader->load($file);

        $sheet = $objExcel->getSheet();
        $rowNum = $sheet->getHighestRow();
        $columnNum = $sheet->getHighestColumn();

        $rowData = $sheet->rangeToArray('A3:' . $columnNum . ($rowNum), NULL, TRUE, FALSE);

        foreach ($rowData as $key => $val) {

            $data['order_num'] = $val[0]; //序号
            $data['name'] = intval($val[3]).'元天猫超市卡'; //名称
            $data['code'] = Crypt::encryptByCard($val[1]); //卡号
            $data['passwd'] = Crypt::encryptByCard($val[2]); //密码
            $data['add_time'] = time();

            if (UserGrowthCards::insert($data)->rowCount()) {
                $id = UserGrowthCards::id();
                cTMallCard::rPushCard($id,NewUserGrowth::USER_GROWTH_T_MALL_CARD_KEY);
                Log::debug('导入天猫卡####',[$key]);
            };
        }

        $success = new MessageBag([
            'title' => '上传成功'
        ]);

        return redirect('/admin/activity/index')->with(compact('success'));
    }

    /**
     * form
     * @param $baseForm
     */
    private function _getForm($baseForm): void
    {
        $baseForm->file('excel', '上传Excel')->required()->removable()->help('请认真核对excel格式');
    }



}